<template>
  <div class="news-activity">
    <CustomSwiper :data="activityBanner" controls @slide-click="handleBanner" />
    <!-- <Banner class="h-[100%] news-activity-banner" :slides="activityBanner" @slide-click="handleBanner" /> -->
    <div class="news-activity-content">
      <div class="news-activity-content-header flex-wrap">
        <div class="news-activity-content-header-title">
          {{ activityTile }}
        </div>
        <ClientOnly>
          <cascade-selector
            v-model="filterParams.city"
            :customOptions="cityList"
            :placeholder="$t('activity.city')"
            @change="handleChangePlace"
          />
          <d-input v-model="searchText" class="flex-1 min-w-[100px]" :maxlength="100" :placeholder="$t('activity.searchPlaceholder')" @keypress.enter="search">
            <template #prefix>
              <GIcon name="gt-search" />
            </template>
          </d-input>
          <d-date-picker-pro 
            class="news-activity-content-header-date" 
            v-model="filterParams.dateTime"
            format="YYYY-MM" 
            type="month" 
            @confirmEvent="handleTime" 
            :placeholder="$t('common.selectTime')"
            />
        </ClientOnly>
        <SwitchTab v-model="activeTab" :tabs-list="tabsList" @onTabChange="handleTabChange" />
      </div>
      <template v-if="activeTab === 'activity-view'">
        <div class="news-activity-content-type">
          <ActivityTypeSelect v-model="filterParams.type" :types="activityTypeList" @change="handleChangeType" />
        </div>
        <ul v-if="showList.length" class="news-activity-content-list">
          <template v-for="(item, index) in showList">
            <li v-if="showIndex > index" :key="index">
              <ActivityCard :activity="item" />
            </li>
          </template>
        </ul>
        <EmptyData v-else-if="showList.length === 0" :hide-icon="false" class="h-full flex-1" />
        <div class="flex justify-center mt-[32px]" v-if="showIndex < showList.length">
          <div class="news-activity-content-list-more" @click="handleMore">
            {{ $t('common.more') }}
            <GIcon name="gt-line-down" />
          </div>
        </div>
      </template>
      <template v-if="activeTab === 'calendar-view'">
        <ActivityDetails v-if="!isPhone() && currentDateData" :data="currentDateData" @handleBack="handleBack">
          <template #checkbox>
            <ActivityTypeSelect v-model="filterParams.type" :types="activityTypeList" @change="handleChangeType" />
          </template>
        </ActivityDetails>
        <Calendar 
          v-else 
          ref="calendarRef"
          :dataList="showList"
          :allDataList="activityList"
          :chooseDate="dateTime"
          @dateSelected="handleDateSelected" 
          @currentMonth="changeCurrentMonth"
        >
          <template #checkbox>
            <ActivityTypeSelect v-model="filterParams.type" :types="activityTypeList" @change="handleChangeType" />
          </template>
        </Calendar>
        <EmptyData 
          v-if="
            !isPhone() &&
            currentDateData &&
            ((currentDateData.data.length &&
            !currentDateData.data.find((item: { show: boolean; }) => item.show)) || !currentDateData?.data.length )
          "
          :hide-icon="false"
          class="h-full flex-1"
        />
      </template>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Carousel as DCarousel, CarouselItem as DCarouselItem } from 'vue-devui/carousel'
import { useTimeFormat } from '@/composables/hooks/useTimeFormat'
import allData from '@/pages/Data/activity.json'
import StatusTag from './components/StatusTag.vue'
import { useI18n } from 'vue-i18n';
import Banner from './components/banner.vue'
import CascadeSelector from '@/components/CascadeSelector/index.vue'
import SwitchTab from './components/switchTab.vue'
import ActivityCard from './components/activityCard.vue'
import ActivityTypeSelect from './components/activityTypeSelect.vue'
import Calendar from '@/components/Calendar/index.vue'
import ActivityDetails from './components/activityDetails.vue'
import CustomSwiper from '@/components/CustomSwiper/index.vue'
import isPhone from '@/utils/isPhone';
import { keepAliveComponentName } from '@/constant';
const { t } = useI18n()
const { formatTime } = useTimeFormat();
// 获取cookie里参数
const lan = useCookie('lang').value || 'zh';

const currentDateData = ref(null);

let data = allData[lan] || allData.zh;

const calendarRef = ref(null);
// 对取到的数据做处理（排序，状态）
data.sort((a: { startTime: string; }, b: { startTime: string; }) => Number(new Date(b.startTime)) - Number(new Date(a.startTime)));
const activityList = data.map((item: { startTime: string; endTime: string; hostCity: string; hostProvince: string; }) => {
  const currentTime = new Date();
  const startTimes = new Date(item.startTime);
  const endTimes = new Date(item.endTime);
  return {
    ...item,
    show: true,
    status: currentTime < startTimes ? 0 : currentTime > endTimes ? 2 : 1,
  }
})

// 获取省份和城市
const cityList = Array.from(activityList.reduce((map: Map<string, { value: string; label: string; children: { value: string; label: string; }[] }>, item) => {
  const hostProvince = item.hostProvince || '';
  const hostCity = item.hostCity || '';
  if (!hostProvince || !hostCity) return map;

  // 如果省份不存在，则创建新的省份对象
  if (!map.has(hostProvince)) {
    map.set(hostProvince, { value: hostProvince, label: hostProvince, children: [] });
  }
  // 获取当前省份对象
  const hostProvinceObj = map.get(hostProvince);
  // 确保 hostProvinceObj 存在且有 children 属性
  if (hostProvinceObj && hostProvinceObj.children) {
    // 检查城市是否已存在
    const cityExists = hostProvinceObj.children.some(c => c.value === hostCity);
    if (!cityExists) {
      hostProvinceObj.children.push({ value: hostCity, label: hostCity });
    }
  }
  
  return map;
}, new Map()).values());

// 获取isBanner为1的活动作为横幅内容，如果不足4个则补充其他活动
const getBannerActivities = () => {
  // isBanner为1的活动
  const bannerActivities = activityList.filter((item: any) => item.isBanner).slice(0, 4);
  
  // 如果不足4个，按时间顺序补充
  const otherActivities = activityList.filter((item: any) => !item.isBanner);
  const neededCount = 4 - bannerActivities.length;
  
  return [...bannerActivities, ...otherActivities.slice(0, neededCount)];
}
const activityBanner = ref(getBannerActivities())

// 获取活动类型，liveBroadcastType
const activityTypeList = ref(activityList
  .map((item: any) => item.liveBroadcast)
  .filter((item: any, index: number, self: any) => item && self.indexOf(item) === index)
)

const showIndex = ref(8)
const showList = ref(activityList)
const filterParams = ref({
  dateTime: null,
  city: [],
  type: [...activityTypeList.value]
})

const searchText = ref('')
const activeTab = ref('activity-view')
const activityTile = computed(() => {
  return currentDateData.value ? t('activity.todayActivity') : t('activity.recentActivity')
})
const tabsList = ref([
  {
    id: 'activity-view',
    icon: 'gt-plane-activity',
    activeIcon: 'gt-plane-activity-red',
    title: t('activity.activityView')
  },
  {
    id: 'calendar-view',
    icon: 'gt-plane-date-defult',
    activeIcon: 'gt-plane-date-red',
    title: t('activity.calendarView')
  },
])

function search() {
  navigateTo({
    name: 'search',
    query: {
      search: searchText.value,
      tab: 'activity'
    }
  })
}

const handleDateSelected = (data: any) => {
  currentDateData.value = data
  filterParams.value.dateTime = data.date
  console.log('data', data)
}

const handleBack = () => {
  currentDateData.value = null
}

// 过滤时间
const handleTime = () => {
  showIndex.value = 8
  handleFilter();
  currentDateData.value = null;
  if (calendarRef.value) {
    calendarRef.value.changeMonth(new Date(filterParams.value.dateTime || new Date()).getFullYear(), new Date(filterParams.value.dateTime || new Date()).getMonth())
  }
}

function handleBanner({ slide, index }: { slide: any, index: number }) {
  window.open(`/activity/${slide.id}`, '_blank');
}

function handleMore() {
  showIndex.value += 8
}

// 处理过滤
const handleFilter = () => {
  let showData = activityList;
  if (filterParams.value.city.length) { 
    showData = activityList.filter((item: { hostCity: string; }) => item.hostCity === filterParams.value.city[1])
  }
  showData = showData.filter((item: { liveBroadcast: string; }) => 
    !item.liveBroadcast || filterParams.value.type.includes(item.liveBroadcast)
  )
  if (filterParams.value.dateTime) {
    showData = showData.filter((item: { startTime: string; endTime: string; }) => {
      const selectedMonth = formatTime(filterParams.value.dateTime, 'YYYY-MM');
      const startMonth = formatTime(item.startTime, 'YYYY-MM');
      const endMonth = formatTime(item.endTime, 'YYYY-MM');
      
      // 检查选择的月份是否在活动的开始月份和结束月份之间（包含边界）
      return selectedMonth >= startMonth && selectedMonth <= endMonth;
    })
  }
  showList.value = showData
}

// 过滤地点
const handleChangePlace = (place: string[]) => {
  showIndex.value = 8
  filterParams.value.city = place
  handleFilter();
  if (currentDateData.value) {
    currentDateData.value.data?.forEach((item: { hostCity: string; }) => {
      item.show = item.hostCity === place[1]
    })
  }
}

// 过滤活动类型
const handleChangeType = (types: string[]) => {
  showIndex.value = 8
  filterParams.value.type = types
  handleFilter();
  if (currentDateData.value) {
    currentDateData.value.data?.forEach((item: { liveBroadcast: string; }) => {
      item.show = !item.liveBroadcast || types.includes(item.liveBroadcast);
    })
  }
  if (calendarRef.value) {
    calendarRef.value.changeSelectDate(types)
  }
}

const changeCurrentMonth = (date: Date) => {
  filterParams.value.dateTime = date
  handleFilter();
}
const handleTabChange = (tab: string) => {
  if (tab === 'calendar-view' &&  filterParams.value.dateTime) {
    calendarRef.value.changeMonth(new Date(filterParams.value.dateTime).getFullYear(), new Date(filterParams.value.dateTime).getMonth())
  }
  // TODO
}

defineOptions({
  name: keepAliveComponentName.Activity
})

useSeoMeta({
  charset: 'utf-8',
  title: () => t('activity.tdk.title'),
  ogTitle: () => t('activity.tdk.title'),
  description: () => t('activity.tdk.desc'),
  ogDescription: () => t('activity.tdk.desc'),
  keywords: () => t('activity.tdk.keyword'),
  ogKeywords: () => t('activity.tdk.keyword'),
})
</script>

<style lang="scss" scoped>
.news-activity {
  color: #3B3E55;

  &-bg {
    background: url('@/assets/img/activity-bg.png') no-repeat;
    background-size: cover;
  }

  &-banner {
    padding: 0 0 32px;
  }

  &-content {
    margin: auto;
    margin-top: 16px;
    max-width: 1200px;

    &-header {
      display: flex;
      align-items: center;
      gap: 32px;
      padding-bottom: 16px;

      &-title {
        background: linear-gradient(90deg, #2951E0 0%, #8A25D9 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: #0000;
        font-weight: 600;
        font-size: 20px;
      }
    }

    &-type {
      height: 32px;
      display: flex;
      align-items: center;
    }

    &-list {
      display: grid;
      grid-template-columns: repeat(4, calc(25% - 12px));
      gap: 16px;
      margin-top: 16px;

      &-item {
        display: flex;
        align-items: center;
        border-radius: 4px;
        cursor: pointer;
        padding-right: 16px;
        gap: 16px;

        &:hover {
          background: #F9F9FB;
        }

        img {
          border-radius: 4px;
          object-fit: cover;
        }

        &-time {
          padding: 14px 16px;
        }

        &-date {
          font-size: 16px;
          font-weight: 600;
          color: #000;
          font-size: 20px;
        }

        &-title {
          font-weight: 600;
          font-size: 16px;
        }

        &-img {
          border-left: 1px solid #F1F1F8;
        }

        &.g-link:hover {
          color: inherit;
        }
      }

      &-more {
        cursor: pointer;

        &:hover {
          color: #2951E0;

          svg {
            color: #2951E0 !important;
          }
        }
      }
    }
  }
}

@media screen and (max-width: 1204px) {
  .news-activity-content {
    &-list {
      grid-template-columns: repeat(2, calc(50% - 8px));
    }
  }
  :deep(.activity-card__image) {
    height: 150px;
  }
  :deep(.carousel-viewport) {
    height: 180px!important;
  }
}

@media screen and (max-width: 768px) {
  .news-activity-content{
    &-list {
      grid-template-columns: repeat(1, 100%);
    }
    :deep(.activity-card__image) {
      height: 190px;
    }
  }
  .news-activity-banner {
    padding: 0 0 16px;
  }
  .news-activity-content-header{
    gap: 16px;
    &-date {
      width: 145px;
    }
  }
  :deep(.carousel-viewport) {
    height: 140px!important;
  }
}
</style>
